package org.spring.cloud.service.impl;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spring.cloud.constant.Constants;
import org.spring.cloud.enums.ModuleEnum;
import org.spring.cloud.manager.SeckillManager;
import org.spring.cloud.service.GenerateOrderService;
import org.spring.cloud.service.SeckillService;
import org.spring.cloud.util.CacheUtils;
import org.spring.cloud.util.Result;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SeckillServiceImpl implements SeckillService{

	private static final Logger logger = LoggerFactory.getLogger(SeckillServiceImpl.class);
	
	@Autowired
	private SeckillManager seckillManager;
	@Autowired
	private RedisTemplate<String, Object> redisTemplate;
	@Autowired
	private RedissonClient  redissonClient;
	@Autowired
	private GenerateOrderService generateOrderService;
	@Autowired
    private AmqpTemplate amqpTemplate;
	
	@Override
	public Result<Boolean> secikllRush(Long userId,Long seckllId) {
		Result<Boolean> result = new Result<>(true);
		String cacheKey = CacheUtils.cacheKeySet(ModuleEnum.SECKILL, seckllId.toString());
		RLock lock = redissonClient.getLock(ModuleEnum.SECKILL.getCode());
		try {
			lock.lock();
			Double total = (Double) this.redisTemplate.opsForValue().get(cacheKey);
			//获取活动数量
			if(total <=0) {
				result.setSuccess(false);
				result.setMessage("对不起，你来晚了。。。");
				logger.info("对不起，用户{}你来晚了，剩余数量{}",userId,total);
				return result;
			}
			result  = this.seckillManager.secikllRush(userId,seckllId);
			if(!result.isSuccess()) {
				return result;
			}
			//缓存数量修改成扣减后的
			total = total -1;
			this.redisTemplate.opsForValue().set(cacheKey, total);
			logger.info("恭喜用户{}抢到了一个，剩余数量{}",userId,total);
			logger.info("订单号"+this.generateOrderService.generateOrder(Constants.PREFIX_B, 6));
			//发送MQ消息
			this.sendMq();
		} finally {
			lock.unlock();
		}
		return result;
	}
	
	/**
	 *发送mq消息 
	 */
	private void sendMq() {
		this.amqpTemplate.convertAndSend(Constants.PARK_QUEUE, "呵呵");
	}
	
}
